/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.client.transport;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import org.creativor.rayson.client.Rayson;
import org.creativor.rayson.client.transport.http.HttpConnection;
import org.creativor.rayson.util.LangUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An {@link HttpConnection} pool.
 * 
 * @author creativor
 */
public class ConnectionPool {

	/**
	 * Monitor thread for this pool.
	 * 
	 * @author creativor
	 */
	private class Monitor extends Thread {
		private Monitor() {
			setName("Connection pool monitor thread of Rayson");
			setDaemon(true);
		}

		@Override
		public void run() {
			LOG.info(getName() + " starting ...");
			super.run();
		}
	}

	private static ConnectionPool POOL = new ConnectionPool();

	/**
	 * Get the singleTon pool.
	 * 
	 * @return
	 */
	public static ConnectionPool getPool() {
		return POOL;
	}

	private final Map<InetSocketAddress, ServerAgent> servers;
	private final AtomicLong CONNECTION_UID;
	private final Monitor monitor;
	private static Logger LOG = LoggerFactory.getLogger(ConnectionPool.class);

	private ConnectionPool() {
		servers = new HashMap<InetSocketAddress, ServerAgent>();
		CONNECTION_UID = new AtomicLong();
		monitor = new Monitor();
	}

	/**
	 * Get an {@link HttpConnection} out of this pool.
	 * 
	 * @param serverAddr
	 *            The server address.
	 * @return An new {@link HttpConnection} or, an cached
	 *         {@link HttpConnection} in this pool.
	 * @throws IOException
	 *             If any IO error.
	 */
	public HttpConnection getConnection(final InetSocketAddress serverAddr)
			throws IOException {
		LangUtil.testNullArgument(serverAddr, "Server address");
		final ServerAgent server = getOrCreateAgent(serverAddr);
		return server.getConnection();
	}

	/**
	 * @return Net connection unique id.
	 */
	long getNextConnId() {
		return CONNECTION_UID.getAndIncrement();
	}

	private synchronized ServerAgent getOrCreateAgent(
			final InetSocketAddress serverAddr) {
		ServerAgent agent = servers.get(serverAddr);
		if (agent == null)
			agent = new ServerAgent(this, serverAddr);
		servers.put(serverAddr, agent);
		return agent;
	}

	/**
	 * Initialize this pool. Invoked by {@link Rayson} client only.
	 */
	public void initialize() {
		monitor.start();
	}

	/**
	 * Remove an http connection from this pool.
	 * 
	 * @param httpConn
	 */
	void remove(final HttpConnectionImpl httpConn) {
		httpConn.getAgent().remove(httpConn.getId());
	}
}
